﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;

namespace Lightray.Hattrick.ChppLib.EntityTypes
{
    public class MatchEvent
    {
        public int Index { get; private set; }
        public int Minute { get; private set; }
        public Player SubjectPlayer { get; internal set; }
        public Team SubjectTeam { get; internal set; }
        public string Description { get; private set; }      

        internal int SubjectPlayerId { get; private set; }
        internal int SubjectTeamId { get; private set; }
       
        //public string EventKey { get; private set; }
        //public Player ObjectPlayer { get; internal set; }
        //internal int ObjectPlayerId { get; private set; }        

        protected MatchEvent() { }

        public static IList<MatchEvent> FromEventListNode(XElement eventListNode)
        {
            List<MatchEvent> ret = new List<MatchEvent>();
            foreach (var eventNode in eventListNode.Descendants("Event"))
                ret.Add(MatchEvent.FromEventNode(eventNode));
            return ret;
        }

        private static MatchEvent FromEventNode(XElement eventNode)
        {
            HattrickXmlReader reader = new HattrickXmlReader(eventNode);
            return new MatchEvent()
            {
                Index = reader.ReadAttributeNumber("Event", "Index"),
                Minute = reader.ReadNumber("Minute"),
                SubjectPlayerId = reader.ReadNumber("SubjectPlayerID"),
                SubjectTeamId = reader.ReadNumber("SubjectTeamID"),
                Description = escapeHtml(reader.ReadString("EventText")),
                //ObjectPlayerID = reader.ReadNumber("ObjectPlayerID"),
                //EventKey = reader.ReadString("EventKey"),
            };
        }

        public static string escapeHtml(string htmlString)
        {
            while (htmlString.Contains("<"))
            {
                int startIndex = htmlString.IndexOf("<");
                int endIndex = htmlString.IndexOf(">") + 1;
                htmlString = htmlString.Remove(startIndex, endIndex - startIndex);
            }
            return htmlString;
        }

        public override string ToString()
        {
            return string.Format("{0} Min: {1}", Minute, Description);
        }
    }
}
